//
//  SQRefreshControl.swift
//  SwiftWeibo
//
//  Created by 苏强 on 16/12/9.
//  Copyright © 2016年 suqianghotel. All rights reserved.
//

import UIKit

/// 刷新事件触发高度
private let SQRefreshTriggerHeight:CGFloat = 80

enum SQRefreshState {
    /// 正常状态
    case normal
    
    /// 将要刷新
    case willRefresh
    
    /// 正在刷新
    case isRefreshing
    
}

class SQRefreshControl: UIControl {
    
    var refreshView: SQRefreshView! = SQRefreshView.refreshView()
    
    var scrollView: UIScrollView?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setupUI()
    }
    
    
    
    
    open var isRefreshing: Bool {
        return false
    }
    
    
    override func willMove(toSuperview newSuperview: UIView?) {
    
        super.willMove(toSuperview: newSuperview)
        
        guard let sc = newSuperview as? UIScrollView   else {
            return
        }
        
        scrollView = sc
        
        scrollView?.addObserver(self, forKeyPath:"contentOffset", options: [], context: nil)
        
    }
    
    
    override func removeFromSuperview() {
        
        superview?.removeObserver(self, forKeyPath: "contentOffset")
        
        super.removeFromSuperview()
    }
    
    
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        
        guard let sc = scrollView else {
            return
        }
        

        var scH = -(sc.contentInset.top + sc.contentOffset.y)
        
        if self.refreshView.refreshState == .isRefreshing {
            scH += SQRefreshTriggerHeight
        }
        
        if scH < 0
        {
            return
        }
        
        print(sc.contentInset)
        
        self.frame = CGRect(x: 0, y: -scH, width: sc.bounds.width, height: scH)
        print(self.frame)
        
        
        if sc.isDragging {
            if scH > SQRefreshTriggerHeight && refreshView.refreshState == .normal      // 正在下拉并超过临界点
            {
                print("超过临界点")
                refreshView.refreshState = .willRefresh
            }
            else if scH <= SQRefreshTriggerHeight && refreshView.refreshState == .willRefresh
            {
                print("未过临界点，")
                refreshView.refreshState = .normal
            }
        }
        else
        {
            if self.refreshView.refreshState == .willRefresh // 超过临界点, 并释放
            {
                print("刷新")
                beginRefreshing()
                
                sendActions(for: .valueChanged)
            }
        }
        
        
    }
    
    open func beginRefreshing()
    {
        print("beginRefreshing")
        
        guard let sc = scrollView else {
            return
        }
        
        if self.refreshView.refreshState == .isRefreshing {
            return
        }
        
        self.refreshView.refreshState = .isRefreshing
        
        var inset = sc.contentInset
        inset.top += SQRefreshTriggerHeight
        sc.contentInset = inset
        
    }
    
    
    
    open func endRefreshing()
    {
        print("endRefreshing")
//        return
        guard let sc = scrollView else {
            return
        }
        
        if self.refreshView.refreshState != .isRefreshing {
            return
        }
        
        self.refreshView.refreshState = .normal
        
        var inset = sc.contentInset
        inset.top -= SQRefreshTriggerHeight
        sc.contentInset = inset
   
//        UIView.animate(withDuration: 0.25){
        
//            self.refreshView.frame = CGRect(x: 0, y: -scH, width: sc.bounds.width, height: scH)
//        }
        
        
    }
    
    
    private func setupUI()
    {
        
        self.addSubview(refreshView)
        
//        self.backgroundColor = super.backgroundColor
        
        self.backgroundColor = UIColor.red
        self.refreshView.backgroundColor = UIColor.orange
        
        self.clipsToBounds = true
        
        refreshView.translatesAutoresizingMaskIntoConstraints = false
        
        addConstraint(NSLayoutConstraint(item: refreshView, attribute: .bottom, relatedBy: .equal, toItem: self, attribute: .bottom, multiplier: 1, constant: -10))
        
        addConstraint(NSLayoutConstraint(item: refreshView, attribute: .centerX, relatedBy: .equal, toItem: self, attribute: .centerX, multiplier: 1, constant: 0))
        
        addConstraint(NSLayoutConstraint(item: refreshView, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: refreshView.bounds.height))
        
        addConstraint(NSLayoutConstraint(item: refreshView, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: refreshView.bounds.width))
        
        
    }
    
}
